package com.imooc.controller;

import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

/**
 * FileName: WeixinController.java
 * Description: 微信Controller - 手工调试演示用
 *
 * @author HuangRI(874668739 @ qq.com)
 * @version 1.0
 * @date 2020/12/24
 */
@Deprecated
@RestController
@Slf4j
@RequestMapping("/weixin")
public class WeixinController {
    /**
     * 以下为微信授权（https://developers.weixin.qq.com/doc/offiaccount/OA_Web_Apps/Wechat_webpage_authorization.html）：
     * 第一步：用户同意授权，获取code
     * 第二步：通过code换取网页授权access_token
     * 第三步：刷新access_token（如果需要），这里就可以拿到用户openid
     *
     */

    /**
     * 用户通过https://open.weixin.qq.com/connect/oauth2/authorize?appid=APPID&redirect_uri=http://域名（用natapp内网穿透）/sell/weixin/auth&response_type=code&scope=snsapi_base&state=STATE#wechat_redirect
     * 拿到微信授权用以获取access_token的code
     * @param code
     */
    @GetMapping("/auth")
    public void auth(@RequestParam("code") String code) {
        log.info("【认证】获取到微信授权code={}", code);

        // TODO 运行时需要需修改这两个【appid、secret】
        String appid = "公众号的唯一标识APPID";
        String secret = "公众号的appsecret";
        String weixinAccessTokenUrl = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + appid + "&secret=" + secret + "&code=" + code + "&grant_type=authorization_code";
        /**
         {
         "access_token":"ACCESS_TOKEN",
         "expires_in":7200,
         "refresh_token":"REFRESH_TOKEN",
         "openid":"OPENID",
         "scope":"SCOPE"
         }
         */
        RestTemplate restTemplate = new RestTemplate();
        String accessTokenJsonStr = restTemplate.getForObject(weixinAccessTokenUrl, String.class);
        log.info("【认证】获取到的accessTokenJsonStr={}", accessTokenJsonStr);
    }
}
